
//  SQLite.m
//  ChinaMerchantBank
//
//  Created by chen wei on 13-6-28.
//  Copyright (c) 2013年 xguanjia. All rights reserved.
//

#import "SQLite.h"

    // Private methods
@interface SQLite (Private)

@end



@implementation SQLite
@synthesize m_sql;
@synthesize m_dbName;

- (id) initWithDbName:(NSString*)dbname
{
    self = [super init];
    if (self != nil) {
        if ([self openOrCreateDatabase:dbname]) {
            [self closeDatabase];
        }
    }
    return self;
}

- (id) init
{
    NSAssert(0,@"Never Use this.Please Call Use initWithDbName:(NSString*)");
    return nil;
}


-(BOOL)openOrCreateDatabase:(NSString*)dbName
{
    self.m_dbName = dbName;
    NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [path objectAtIndex:0];
    if(sqlite3_open([[documentsDirectory stringByAppendingPathComponent:dbName] UTF8String],&m_sql) != SQLITE_OK)
        {
        NSLog(@"创建数据库失败");
        return    NO;
        }
    return YES;
}

-(BOOL)createTable:(NSString*)sqlCreateTable
{
    if (![self openOrCreateDatabase:self.m_dbName]) {
        return NO;
    }
    char *errorMsg;
    if (sqlite3_exec (self.m_sql, [sqlCreateTable  UTF8String],NULL, NULL, &errorMsg) != SQLITE_OK)
        {
        NSLog(@"创建数据表失败:%s",errorMsg);
        return NO;
        }
    //[self closeDatabase];
    return YES;
}


-(void)closeDatabase
{
    sqlite3_close(self.m_sql);
}


-(BOOL)updateTable:(NSString*)sqlUpdate
{
    if (![self openOrCreateDatabase:self.m_dbName]) {
        return NO;
    }
    char* errorMsg = NULL;
    if(sqlite3_exec(self.m_sql, [sqlUpdate UTF8String],0, NULL, &errorMsg) == SQLITE_OK){
            //[self closeDatabase];
        return YES;
    }else {
        printf("更新表失败:%s",errorMsg);
        [self closeDatabase];
        return NO;
    }
    
    
    return YES;
}

-(BOOL)updateGreatTable:(NSMutableArray*)sqlUpdate
{
    @try{
        if (![self openOrCreateDatabase:self.m_dbName]) {
            return NO;
        }
        char* errorMsg = NULL;
        if(sqlite3_exec(self.m_sql, "BEGIN", NULL, NULL, &errorMsg)==SQLITE_OK){
            NSLog(@"启动事务成功");
            sqlite3_free(errorMsg);
            for (NSString *statement in sqlUpdate) {
                sqlite3_exec(self.m_sql, [statement UTF8String],0, NULL, &errorMsg);
            }
            if (sqlite3_exec(self.m_sql,"COMMIT", NULL, NULL, &errorMsg)==SQLITE_OK) {
                NSLog(@"提交事务成功");
            }
            sqlite3_free(errorMsg);
        }else{
                //sqlite3_free(errorMsg);
        }
    }
    @catch(NSException *e){
        char *errorMsg;
        if(sqlite3_exec(self.m_sql, "ROLLBACK", NULL, NULL, &errorMsg)==SQLITE_OK){
            NSLog(@"回滚事务成功");
        }
        sqlite3_free(errorMsg);
    }
    return YES;
}

-(NSArray*)querryTable:(NSString*)sqlQuerry
{
    if (![self openOrCreateDatabase:self.m_dbName]) {
        return nil;
    }
    int row = 0;
    int column = 0;
    char*    errorMsg = NULL;
    char**    dbResult = NULL;
    NSMutableArray*    array = [[NSMutableArray alloc] init];
    if(sqlite3_get_table(m_sql, [sqlQuerry UTF8String], &dbResult, &row,&column,&errorMsg ) == SQLITE_OK)
        {
        if (0 == row) {
            [self closeDatabase];
            return nil;
        }
        int index = column;
        for(int i = 0; i < row ; i++ ) {
            NSMutableDictionary*    dic = [[NSMutableDictionary alloc] init];
            for(int j = 0 ; j < column; j++ ) {
                if (dbResult[index]) {
                    NSString* value = [NSString stringWithUTF8String:dbResult[index]];
                    NSString*key  = [NSString stringWithUTF8String:dbResult[j]];
//                    key
                    
                    [dic setObject:value forKey:key];
                }
                
                index ++;
            }
            [array addObject:dic];
        }
        
        }else {
            [self closeDatabase];
            return nil;
        }
    
    [self closeDatabase];
    NSArray *returnArray  = [NSArray arrayWithArray:array];
    return returnArray;
}


int  processData(void* arrayResult,int columnCount,char** columnValue, char** columnName)
{
    int i;
        //    [[NSMutableDictionary alloc] init]
    NSMutableDictionary* dic = [NSMutableDictionary dictionary];
    for( i = 0 ; i < columnCount; i ++ )
        {
        if (columnValue[i]) {
            NSString* key = [NSString stringWithUTF8String:columnName[i]];
            NSString* value = [NSString stringWithUTF8String:columnValue[i]];
            [dic setObject:value forKey:key];
        }
        
        }
    
    [(__bridge NSMutableArray*)arrayResult addObject:dic];
        //[dic release];
    return 0;
}

- (NSArray*)querryTableByCallBack:(NSString*)sqlQuerry
{
    if (![self openOrCreateDatabase:self.m_dbName]) {
        return nil;
    }
    
    NSMutableArray* arrayResult = [[NSMutableArray alloc] init];
    @try{
        char *errorMsg;
        if(sqlite3_exec(self.m_sql, "BEGIN", NULL, NULL, &errorMsg)==SQLITE_OK){
                //NSLog(@"启动事务成功");
            sqlite3_free(errorMsg);
            if (sqlite3_exec(self.m_sql,[sqlQuerry UTF8String],processData,(__bridge void*)arrayResult,&errorMsg) != SQLITE_OK) {
                    //printf("查询出错:%s",errorMsg);
            }
            
            if (sqlite3_exec(self.m_sql,"COMMIT", NULL, NULL, &errorMsg)==SQLITE_OK) {
                    //NSLog(@"提交事务成功");
            }
            sqlite3_free(errorMsg);
        }else{
            sqlite3_free(errorMsg);
        }
    }
    @catch(NSException *e){
        char *errorMsg;
        if(sqlite3_exec(self.m_sql, "ROLLBACK", NULL, NULL, &errorMsg)==SQLITE_OK){
                //NSLog(@"回滚事务成功");
        }
        sqlite3_free(errorMsg);
    }
    NSArray *returnArray = [NSArray arrayWithArray:arrayResult];
    return returnArray;
    
}

@end

